import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    teamId: null,
    action: null,
    team: {
      id: null,
      name: '',
      description: '',
      creatorName: '',
      memberCount: 0,
      members: []
    },
    // 添加成员相关数据
    showAddMemberModal: false,
    selectedMember: null,
    memberRole: '成员'
  },

  onLoad(options) {
    if (options.action === 'create') {
      // 创建团队模式
      this.setData({
        action: 'create'
      })
      wx.setNavigationBarTitle({
        title: '创建团队'
      })
    } else if (options.id) {
      // 编辑团队模式
      this.setData({
        teamId: options.id,
        action: 'edit'
      })
      this.loadTeamDetail(options.id)
      wx.setNavigationBarTitle({
        title: '团队详情'
      })
    }
  },

  loadTeamDetail(teamId) {
    // 调用获取团队详情接口
    post(apiPaths.getTeamDetail, { id: teamId }).then(res => {
      if (res.code === 200) {
        const data = res.data
        const team = {
          id: data.team.id,
          name: data.team.name,
          description: data.team.description,
          creatorName: data.team.creator_name,
          memberCount: data.members.length,
          members: data.members || []
        }
        
        this.setData({
          team: team
        })
      } else {
        wx.showToast({
          title: res.message || '获取团队详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '获取团队详情失败',
        icon: 'none'
      })
    })
  },

  onTeamNameInput(e) {
    this.setData({
      'team.name': e.detail.value
    })
  },

  onTeamDescriptionInput(e) {
    this.setData({
      'team.description': e.detail.value
    })
  },

  onSaveTeam() {
    if (!this.data.team.name) {
      wx.showToast({
        title: '请输入团队名称',
        icon: 'none'
      })
      return
    }
    
    if (this.data.action === 'create') {
      // 创建团队
      const userInfo = wx.getStorageSync('userInfo') || {}
      const createdById = userInfo.id
      
      if (!createdById) {
        wx.showToast({
          title: '用户信息错误',
          icon: 'none'
        })
        return
      }
      
      post(apiPaths.createTeam, {
        name: this.data.team.name,
        description: this.data.team.description,
        createdById: createdById
      }).then(res => {
        if (res.code === 200) {
          wx.showToast({
            title: '团队创建成功',
            icon: 'success'
          })
          
          // 返回团队列表页面
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.message || '团队创建失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message || '团队创建失败',
          icon: 'none'
        })
      })
    } else {
      // 更新团队
      post(apiPaths.updateTeam, {
        id: this.data.teamId,
        name: this.data.team.name,
        description: this.data.team.description
      }).then(res => {
        if (res.code === 200) {
          wx.showToast({
            title: '团队更新成功',
            icon: 'success'
          })
          
          // 重新加载团队详情
          this.loadTeamDetail(this.data.teamId)
        } else {
          wx.showToast({
            title: res.message || '团队更新失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message || '团队更新失败',
          icon: 'none'
        })
      })
    }
  },

  onCancel() {
    wx.navigateBack()
  },

  onDeleteTeam() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该团队吗？此操作不可恢复',
      success: (res) => {
        if (res.confirm) {
          // 调用删除团队接口
          post(apiPaths.deleteTeam, {
            id: this.data.teamId
          }).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '团队已删除',
                icon: 'success'
              })
              setTimeout(() => {
                wx.navigateBack()
              }, 1500)
            } else {
              wx.showToast({
                title: res.message || '团队删除失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message || '团队删除失败',
              icon: 'none'
            })
          })
        }
      }
    })
  },

  // 显示添加成员弹窗
  onAddMember() {
    this.setData({
      showAddMemberModal: true,
      selectedMember: null,
      memberRole: '成员'
    })
  },
  
  // 关闭添加成员弹窗
  onCloseAddMemberModal() {
    this.setData({
      showAddMemberModal: false
    })
  },
  
  // 选择成员
  onMemberSelect(e) {
    this.setData({
      selectedMember: e.detail.value
    })
  },
  
  // 角色输入
  onRoleInput(e) {
    this.setData({
      memberRole: e.detail.value
    })
  },
  
  // 确认添加成员
  onConfirmAddMember() {
    if (!this.data.selectedMember) {
      wx.showToast({
        title: '请选择成员',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.teamId) {
      wx.showToast({
        title: '团队ID不能为空',
        icon: 'none'
      })
      return
    }
    
    post(apiPaths.addTeamMember, {
      teamId: this.data.teamId,
      userId: this.data.selectedMember,
      role: this.data.memberRole
    }).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: '成员添加成功',
          icon: 'success'
        })
        
        this.setData({
          showAddMemberModal: false
        })
        
        // 重新加载团队详情
        this.loadTeamDetail(this.data.teamId)
      } else {
        wx.showToast({
          title: res.message || '成员添加失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '成员添加失败',
        icon: 'none'
      })
    })
  },

  onRemoveMember(e) {
    const memberId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要移除该成员吗？',
      success: (res) => {
        if (res.confirm) {
          // 调用删除团队成员接口
          post(apiPaths.removeTeamMember, {
            teamId: this.data.teamId,
            userId: memberId
          }).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '已移除成员',
                icon: 'success'
              })
              // 重新加载团队详情
              this.loadTeamDetail(this.data.teamId)
            } else {
              wx.showToast({
                title: res.message || '移除成员失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message || '移除成员失败',
              icon: 'none'
            })
          })
        }
      }
    })
  },
  
  // 更新成员角色
  onUpdateMemberRole(e) {
    const memberId = e.currentTarget.dataset.id
    const member = this.data.team.members.find(m => m.id == memberId)
    
    if (member) {
      // 这里可以显示一个输入框让用户输入新的角色
      wx.showModal({
        title: '更新角色',
        editable: true,
        placeholderText: '请输入新角色',
        content: member.role,
        success: (res) => {
          if (res.confirm) {
            const newRole = res.content
            if (newRole) {
              post(apiPaths.updateTeamMemberRole, {
                teamId: this.data.teamId,
                userId: memberId,
                role: newRole
              }).then(res => {
                if (res.code === 200) {
                  wx.showToast({
                    title: '角色更新成功',
                    icon: 'success'
                  })
                  // 重新加载团队详情
                  this.loadTeamDetail(this.data.teamId)
                } else {
                  wx.showToast({
                    title: res.message || '角色更新失败',
                    icon: 'none'
                  })
                }
              }).catch(err => {
                wx.showToast({
                  title: err.message || '角色更新失败',
                  icon: 'none'
                })
              })
            }
          }
        }
      })
    }
  }
})